module AuditsHelper
  # Given a <tt>value</tt>, returns the string NONE if the value is <tt>blank?</tt>,
  # otherwise returns the given <tt>value</tt>
  def blank_is_none(value)
    value.blank? ? "NONE" : value
  end

  # Allows you to iterate over a given Audit#change_set. Given a block, each time
  # yield is called, it will return the attribute, the old version and the new
  # version as arguments. If the Audit is a message audit, it will set the new
  # attribute to the audit message.
  #
  # Example:
  #  <% change_set_iter(audit.change_set) do |attr, old, new| %>
  #    <p class="audit"><strong><%=h attr %></strong>
  #      <% if audit.message %>
  #        <em><%= new %></em>
  #      <% else %>
  #        changed from <em><%=h old %></em> to <em><%=h new %></em>.
  #      <% end %>
  #    </p>
  #  <% end %>
  def change_set_iter(change_set, &block)
    change_set.each_pair do |attr, change|
      if change.is_a?(Array)
        old_val = blank_is_none(change.first)
        new_val = blank_is_none(change.last)
      else
        old_val = blank_is_none("")
        new_val = blank_is_none(change)
      end

      yield attr.titleize, old_val, new_val
    end
  end
end
